//
//  OAuthViewController.swift
//  dwdWb
//
//  Created by Dengdwd on 15/10/6.
//  Copyright © 2015年 dwd. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {

    
    var webView: UIWebView {
        get{
            //将根视图控制器强转为webView
            return view as! UIWebView
        }    
    }

    override func viewDidLoad() {
        super.viewDidLoad()
//        print(view)
        loadOAuthPage()
    }
    private func loadOAuthPage () {
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oAuthPage()))
        
    }
  
    @IBAction func autoLogin() {
//        print(__FUNCTION__)
        
        let jsString1 = "document.getElementById('userId').value = '530249530@qq.com'"
        let jsString2 = "document.getElementById('passwd').value = 'Twandi0225'"
        webView.stringByEvaluatingJavaScriptFromString(jsString1)
        webView.stringByEvaluatingJavaScriptFromString(jsString2)
    }
    @IBAction func close() {
//        print(__FUNCTION__)
        dismissViewControllerAnimated(true, completion: nil)
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        let titleStr = "document.title"
        let webTitle = webView.stringByEvaluatingJavaScriptFromString(titleStr)
        title = webTitle
        SVProgressHUD.dismiss()
    }
//    界面刷新开始加载就会调用.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
//        print(urlString)
        if urlString.hasPrefix("https://api.weibo.com/") {
        return true
        }
        if !urlString.hasPrefix(NetworkTools.sharedTools.Wb_redirect_uri) {
        return false
        }
        if let query = request.URL?.query {
        let codeStr = "code="
        let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            loadToken(code)
        }
        return false
    }
    
    private func loadToken(code:String) {
    NetworkTools.sharedTools.loadToken(code, completion: { (dict, error) -> () in
        if error != nil {
        SVProgressHUD.showInfoWithStatus("您的网络不给力哦")
        return
        }
        let acount = UserAcount(dict: dict!)
        
        acount.loadUserInfo { (error) -> () in
            if error != nil {
            SVProgressHUD.showInfoWithStatus("您的网络不给力哦")
            return
            }
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(DWDSwiftRootviewControllerNotification, object: nil)
            })
        }
        })
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
}
